<?php

try {
	// Require custom exception class:
	require_once 'Objects/PCException.php';
	
	// Require settings and all modules:
	require_once 'Modules/Logger.php';
	require_once 'settings.php';
	
	// Begin of request:
	Logger::log("index", "Start of request from " . HTTPHandler::getIP() . ".");
	
	// Always return the current UNIX timestamp:
	HTTPHandler::setHeader("UnixStamp", time());
	
	// Try to fetch the operation:
	$operationFactory = new OperationFactory();
	$operationName = HTTPHandler::getRESTOperation();
	$operation = $operationFactory->fromName($operationName);
	if (!$operation) {
		throw new PCException("Operation '" . $operationName . "' not found.", 404);
	}
	
	// Execute operation:
	$operation->execute();
	
	// Flush HTTPHandler:
	HTTPHandler::flush();
	
	// Write logFile:
	Logger::write();
} catch (PCException $e) {
	// Clear buffer and display error:
	HTTPHandler::clear();
	HTTPHandler::add($e->getXML());
	HTTPHandler::flush();
	
	// Log error aswell:
	$fName = str_replace(".csv", "_ERROR.xml", Logger::getFileName());
	$f = fopen($fName, "w+");
	fwrite($f, $e->getXML());
	fclose($f);
	Logger::log("index", "PCException caught and saved in '" . $fName . "'.");
	Logger::write();
} catch (Exception $e) {
	// Clear buffer and display error:
	HTTPHandler::clear();
	HTTPHandler::add("<error/>");
	HTTPHandler::flush();
	
	// Log error aswell:
	$fName = str_replace(".csv", "_ERROR.txt", Logger::getFileName());
	$f = fopen($fName, "w+");
	fwrite($f, "CODE: " . $e->getCode() . "\r\n");
	fwrite($f, "MESSAGE: " . $e->getMessage(). "\r\n");
	fwrite($f, "FILE: " . $e->getFile() . "\r\n");
	fwrite($f, "LINE: " . $e->getLine() . "\r\n");
	fwrite($f, "TRACE: \r\n" . $e->getTraceAsString() . "\r\n");
	fclose($f);
	Logger::log("index", "UNKNOWN Exception caught and saved in '" . $fName . "'.");
	Logger::write();
}
 ?>